package cn.ug.operation.web.controller;

import cn.ug.activity.bean.CouponRepertoryBean;
import cn.ug.bean.base.DataTable;
import cn.ug.bean.base.Page;
import cn.ug.bean.base.SerializeObject;
import cn.ug.bean.type.ResultType;
import cn.ug.config.AplicationResourceProperties;
import cn.ug.core.SerializeObjectError;
import cn.ug.core.login.LoginHelper;
import cn.ug.feign.CouponRepertoryService;
import cn.ug.feign.MemberUserService;
import cn.ug.feign.PriceService;
import cn.ug.member.bean.response.MemberUserBean;
import cn.ug.operation.bean.*;
import cn.ug.operation.mapper.entity.GuessJoinMember;
import cn.ug.operation.mapper.entity.GuessPriceActivity;
import cn.ug.operation.mapper.entity.GuessRecord;
import cn.ug.operation.service.GuessPriceActivityService;
import cn.ug.operation.service.GuessRecordService;
import cn.ug.util.ExportExcelUtil;
import cn.ug.util.PaginationUtil;
import cn.ug.util.UF;
import cn.ug.web.controller.BaseController;
import cn.ug.web.controller.ExportExcelController;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.concurrent.ThreadLocalRandom;

import static cn.ug.util.ConstantUtil.*;

@RestController
@RequestMapping("price/activity")
public class GuessPriceActivityController extends BaseController {
    @Autowired
    private GuessPriceActivityService guessPriceActivityService;
    @Autowired
    private GuessRecordService guessRecordService;
    @Autowired
    private PriceService priceService;
    @Autowired
    private MemberUserService memberUserService;
    @Autowired
    protected AplicationResourceProperties properties;
    @Autowired
    private CouponRepertoryService couponRepertoryService;

    @GetMapping(value = "/current/time")
    public SerializeObject getCurrentTime() {
        SimpleDateFormat format = new SimpleDateFormat(NORMAL_TIME_FORMAT);
        return new SerializeObject<>(ResultType.NORMAL,"", format.format(Calendar.getInstance().getTime()));
    }

    @GetMapping(value = "/{id}")
    public SerializeObject get(@RequestHeader String accessToken, @PathVariable int id) {
        if(id <= 0) {
            return new SerializeObjectError("00000002");
        }
        GuessPriceActivity entity = guessPriceActivityService.getActivity(id);
        if(null == entity || entity.getId() <= 0) {
            return new SerializeObjectError("00000003");
        }
        return new SerializeObject<>(ResultType.NORMAL, entity);
    }

    @GetMapping(value = "/statistics/{id}")
    public SerializeObject getStatisticsData(@RequestHeader String accessToken, @PathVariable int id) {
        if(id <= 0) {
            return new SerializeObjectError("00000002");
        }
        PriceActivityStatistics entity = guessPriceActivityService.findStatisticsById(id);
        if(null == entity) {
            return new SerializeObjectError("00000003");
        }
        return new SerializeObject<>(ResultType.NORMAL, entity);
    }

    @PostMapping
    public SerializeObject save(@RequestHeader String accessToken, GuessPriceActivity entity) {
        if(null == entity || StringUtils.isBlank(entity.getName())) {
            return new SerializeObjectError("25000020");
        }
        if (StringUtils.isBlank(entity.getNumber())) {
            return new SerializeObjectError("25000021");
        }
        if (StringUtils.isBlank(entity.getStartDate()) || StringUtils.isBlank(entity.getEndDate())) {
            return new SerializeObjectError("25000022");
        }
        if (entity.getGoldWeight() <= 0) {
            return new SerializeObjectError("25000023");
        }
        if (StringUtils.isBlank(entity.getTimePoint())) {
            return new SerializeObjectError("25000024");
        }
        String[] infos = StringUtils.split(entity.getTimePoint(), COLON);
        if (infos == null || infos.length != 2) {
            return new SerializeObjectError("25000028");
        }
        if (StringUtils.isBlank(entity.getStartGuessPoint()) || StringUtils.isBlank(entity.getEndGuessPoint())) {
            return new SerializeObjectError("25000025");
        }
        String[] startInfos = StringUtils.split(entity.getStartGuessPoint(), COLON);
        if (startInfos == null || startInfos.length != 2) {
            return new SerializeObjectError("25000030");
        }
        String[] endInfos = StringUtils.split(entity.getEndGuessPoint(), COLON);
        if (endInfos == null || endInfos.length != 2) {
            return new SerializeObjectError("25000030");
        }
        if (StringUtils.isBlank(entity.getPublishPoint())) {
            return new SerializeObjectError("25000026");
        }
        String[] pubInfos = StringUtils.split(entity.getPublishPoint(), COLON);
        if (pubInfos == null || pubInfos.length != 2) {
            return new SerializeObjectError("25000029");
        }
        if (StringUtils.isBlank(entity.getCouponIds())) {
            return new SerializeObjectError("25000067");
        }
        if (guessPriceActivityService.save(entity)) {
            return new SerializeObject(ResultType.NORMAL, "00000001");
        } else {
            return new SerializeObject(ResultType.ERROR, "00000005");
        }
    }

    @GetMapping(value = "/list")
    public SerializeObject<DataTable<GuessPriceActivity>> list(@RequestHeader String accessToken, Page page, String startDate, String endDate, String number) {
        startDate = UF.toString(startDate);
        endDate = UF.toString(endDate);
        number = UF.toString(number);
        int total = guessPriceActivityService.count(number, startDate, endDate);
        page.setTotal(total);
        if (total > 0) {
            int offset = PaginationUtil.getOffset(page.getPageNum(), page.getPageSize());
            int size = PaginationUtil.getPageSize(page.getPageSize());
            if (page.getPageNum() == 0) {
                offset = 0;
                size = 0;
            }
            List<GuessPriceActivity> list = guessPriceActivityService.query(number, startDate, endDate, offset, size);
            return new SerializeObject<>(ResultType.NORMAL, new DataTable<GuessPriceActivity>(page.getPageNum(), page.getPageSize(), page.getTotal(), list));
        }
        return new SerializeObject<>(ResultType.NORMAL, new DataTable<GuessPriceActivity>(page.getPageNum(), page.getPageSize(), page.getTotal(), new ArrayList<GuessPriceActivity>()));
    }

    @GetMapping(value = "/record/list")
    public SerializeObject<DataTable<EverydayGuessStatisticsBean>> queryRecordList(@RequestHeader String accessToken, Page page, int activityId) {
        int total = guessRecordService.countForRecord(activityId);
        page.setTotal(total);
        if (total > 0) {
            int offset = PaginationUtil.getOffset(page.getPageNum(), page.getPageSize());
            int size = PaginationUtil.getPageSize(page.getPageSize());
            if (page.getPageNum() == 0) {
                offset = 0;
                size = 0;
            }
            List<EverydayGuessStatisticsBean> list = guessRecordService.queryForRecord(activityId, offset, size);
            return new SerializeObject<>(ResultType.NORMAL, new DataTable<EverydayGuessStatisticsBean>(page.getPageNum(), page.getPageSize(), page.getTotal(), list));
        }
        return new SerializeObject<>(ResultType.NORMAL, new DataTable<EverydayGuessStatisticsBean>(page.getPageNum(), page.getPageSize(), page.getTotal(), new ArrayList<EverydayGuessStatisticsBean>()));
    }

    @GetMapping(value = "/guess/member/list")
    public SerializeObject<DataTable<GuessMemberBean>> queryGuessMemberList(@RequestHeader String accessToken, Page page, Integer activityId, String guessDate, Integer guessResult, String memberId, String number) {
        guessDate = UF.toString(guessDate);
        memberId = UF.toString(memberId);
        number = UF.toString(number);
        guessResult = guessResult == null ? 0 : guessResult;
        activityId = activityId == null ? 0 : activityId;
        int total = guessRecordService.countForGuessMembers(activityId, guessDate, guessResult, memberId, number);
        page.setTotal(total);
        if (total > 0) {
            int offset = PaginationUtil.getOffset(page.getPageNum(), page.getPageSize());
            int size = PaginationUtil.getPageSize(page.getPageSize());
            if (page.getPageNum() == 0) {
                offset = 0;
                size = 0;
            }
            List<GuessMemberBean> list = guessRecordService.queryForGuessMembers(activityId, guessDate, guessResult, memberId, number, offset, size);
            return new SerializeObject<>(ResultType.NORMAL, new DataTable<GuessMemberBean>(page.getPageNum(), page.getPageSize(), page.getTotal(), list));
        }
        return new SerializeObject<>(ResultType.NORMAL, new DataTable<GuessMemberBean>(page.getPageNum(), page.getPageSize(), page.getTotal(), new ArrayList<GuessMemberBean>()));
    }

    @GetMapping(value = "/guess/member/statistics/list")
    public SerializeObject<DataTable<GuessMemberStatisticsBean>> queryGuessMemberList(@RequestHeader String accessToken, Page page, String name, String mobile,
                 Integer bindedCard, String startTime, String endTime) {
        bindedCard = bindedCard == null ? 0 : bindedCard;
        name = UF.toString(name);
        startTime = UF.toString(startTime);
        endTime = UF.toString(endTime);
        mobile = UF.toString(mobile);
        int total = guessRecordService.countForGuessMemberStatistics(name, mobile, bindedCard, startTime, endTime);
        page.setTotal(total);
        if (total > 0) {
            int offset = PaginationUtil.getOffset(page.getPageNum(), page.getPageSize());
            int size = PaginationUtil.getPageSize(page.getPageSize());
            if (page.getPageNum() == 0) {
                offset = 0;
                size = 0;
            }
            List<GuessMemberStatisticsBean> list = guessRecordService.queryForGuessMemberStatistics(name, mobile, bindedCard, startTime, endTime, offset, size);
            return new SerializeObject<>(ResultType.NORMAL, new DataTable<GuessMemberStatisticsBean>(page.getPageNum(), page.getPageSize(), page.getTotal(), list));
        }
        return new SerializeObject<>(ResultType.NORMAL, new DataTable<GuessMemberStatisticsBean>(page.getPageNum(), page.getPageSize(), page.getTotal(), new ArrayList<GuessMemberStatisticsBean>()));
    }

    @GetMapping(value = "/guess/member/statistics/export")
    public void exportWithdraw(HttpServletResponse response, String name, String mobile, Integer bindedCard, String startTime, String endTime) {
        bindedCard = bindedCard == null ? 0 : bindedCard;
        name = UF.toString(name);
        mobile = UF.toString(mobile);
        endTime = UF.toString(endTime);
        mobile = UF.toString(mobile);
        List<GuessMemberStatisticsBean> list = guessRecordService.queryForGuessMemberStatistics(name, mobile, bindedCard, startTime, endTime, 0, 0);
        if(list != null && !list.isEmpty()){
            String[] columnNames = { "序号", "手机号","姓名", "绑卡状态", "获得黄金总克重（克）", "获得现金红包总数（个）"};
            String [] columns = {"index",  "mobile", "name", "bindedCard", "gotGold", "couponNum"};
            String fileName = "猜金价参与用户表";
            ExportExcelController<GuessMemberStatisticsRemarkBean> export = new ExportExcelController<GuessMemberStatisticsRemarkBean>();
            export.exportExcel(fileName, fileName, columnNames, columns, wrapStatisticeData(list), response, ExportExcelUtil.EXCEL_FILE_2003);
        }
    }

    private List<GuessMemberStatisticsRemarkBean> wrapStatisticeData(List<GuessMemberStatisticsBean> list) {
        List<GuessMemberStatisticsRemarkBean> beans = new ArrayList<GuessMemberStatisticsRemarkBean>();
        int index = 1;
        for (GuessMemberStatisticsBean bean : list) {
            GuessMemberStatisticsRemarkBean remarkBean = new GuessMemberStatisticsRemarkBean();
            remarkBean.setIndex(index);
            remarkBean.setMobile(bean.getMobile());
            if (StringUtils.isNotBlank(bean.getName())) {
                remarkBean.setName(bean.getName());
            } else {
                remarkBean.setName("N/A");
            }
            if (bean.getBindedCard() == 1) {
                remarkBean.setBindedCard("未绑卡");
            } else if (bean.getBindedCard() == 2) {
                remarkBean.setBindedCard("已绑卡");
            }
            remarkBean.setGotGold(String.valueOf(bean.getGotGold()));
            remarkBean.setCouponNum(String.valueOf(bean.getCouponNum()));
            beans.add(remarkBean);
            index++;
        }
        return beans;
    }

    @GetMapping(value = "/guess/member/export")
    public void exportWithdraw(HttpServletResponse response, int activityId, String guessDate, Integer guessResult) {
        guessDate = UF.toString(guessDate);
        guessResult = guessResult == null ? 0 : guessResult;
        List<GuessMemberBean> list = guessRecordService.queryForGuessMembers(activityId, guessDate, guessResult, "", "", 0, 0);
        if(list != null && !list.isEmpty()){
            String[] columnNames = { "序号", "手机号","用户姓名", "参与时间", "竞猜金价(元/克）", "公布金价（元/克）", "竞猜结果",
                "分享状态", "获得黄金克重奖励（克）", "获得现金红包金额（元）"};
            String [] columns = {"index",  "mobile", "name", "guessTime", "guessPrice", "finalPrice", "guessResult",
                "shareStatus", "gotGold", "couponAmount"};
            String fileName = "参与用户详细总表";
            ExportExcelController<GuessMemberRemarkBean> export = new ExportExcelController<GuessMemberRemarkBean>();
            export.exportExcel(fileName, fileName, columnNames, columns, wrapData(list), response, ExportExcelUtil.EXCEL_FILE_2003);
        }
    }

    private List<GuessMemberRemarkBean> wrapData(List<GuessMemberBean> list) {
        List<GuessMemberRemarkBean> beans = new ArrayList<GuessMemberRemarkBean>();
        int index = 1;
        for (GuessMemberBean bean : list) {
            GuessMemberRemarkBean remarkBean = new GuessMemberRemarkBean();
            remarkBean.setIndex(index);
            remarkBean.setMobile(bean.getMobile());
            if (StringUtils.isNotBlank(bean.getName())) {
                remarkBean.setName(bean.getName());
            } else {
                remarkBean.setName("N/A");
            }
            remarkBean.setGuessTime(bean.getGuessTime());
            remarkBean.setGuessPrice(bean.getGuessPrice());
            remarkBean.setFinalPrice(bean.getFinalPrice());
            if (bean.getGuessResult() == 1) {
                remarkBean.setGuessResult("未公布");
            } else if (bean.getGuessResult() == 2) {
                remarkBean.setGuessResult("已猜中");
            } else if (bean.getGuessResult() == 3) {
                remarkBean.setGuessResult("未猜中");
            }
            if (bean.getShareStatus() == 1) {
                remarkBean.setShareStatus("未分享");
            } else if (bean.getShareStatus() == 2) {
                remarkBean.setShareStatus("已分享");
            }
            if (bean.getGotGold() > 0) {
                remarkBean.setGotGold(String.valueOf(bean.getGotGold()));
            } else {
                remarkBean.setGotGold("N/A");
            }
            if (bean.getCouponAmount() > 0) {
                remarkBean.setCouponAmount(String.valueOf(bean.getCouponAmount()));
            } else {
                remarkBean.setCouponAmount("N/A");
            }
            beans.add(remarkBean);
        }
        return beans;
    }

    @GetMapping(value = "/statistics/list")
    public SerializeObject<DataTable<PriceActivityStatistics>> getStatisticsList(@RequestHeader String accessToken, Page page, String startDate, String endDate, String number) {
        startDate = UF.toString(startDate);
        endDate = UF.toString(endDate);
        number = UF.toString(number);
        int total = guessPriceActivityService.count(number, startDate, endDate);
        page.setTotal(total);
        if (total > 0) {
            int offset = PaginationUtil.getOffset(page.getPageNum(), page.getPageSize());
            int size = PaginationUtil.getPageSize(page.getPageSize());
            if (page.getPageNum() == 0) {
                offset = 0;
                size = 0;
            }
            List<PriceActivityStatistics> list = guessPriceActivityService.queryStatisticsList(number, startDate, endDate, offset, size);
            return new SerializeObject<>(ResultType.NORMAL, new DataTable<PriceActivityStatistics>(page.getPageNum(), page.getPageSize(), page.getTotal(), list));
        }
        return new SerializeObject<>(ResultType.NORMAL, new DataTable<PriceActivityStatistics>(page.getPageNum(), page.getPageSize(), page.getTotal(), new ArrayList<PriceActivityStatistics>()));
    }

    @PutMapping
    public SerializeObject delete(@RequestHeader String accessToken, Integer[] id) {
        if(null == id || id.length <= 0) {
            return new SerializeObjectError("00000002");
        }
        if (guessPriceActivityService.removeInBatch(id)) {
            return new SerializeObject(ResultType.NORMAL, "00000001");
        } else {
            return new SerializeObject(ResultType.ERROR, "00000005");
        }
    }

    @PutMapping("/status")
    public SerializeObject updateStatus(@RequestHeader String accessToken, Integer id, int shelfState) {
        if(null == id || id == 0) {
            return new SerializeObjectError("00000002");
        }
        Integer[] ids = {id};
        if (shelfState == 1) {
            GuessPriceActivity activity = guessPriceActivityService.getUsableActivity();
            if (activity != null && activity.getId() > 0) {
                return new SerializeObjectError("25000027");
            }
        }
        if (guessPriceActivityService.updateShelfState(ids, shelfState)) {
            return new SerializeObject(ResultType.NORMAL, "00000001");
        } else {
            return new SerializeObject(ResultType.ERROR, "00000005");
        }
    }

    @GetMapping(value = "/member/record")
    public SerializeObject<DataTable<MemberGuessRecordBean>> queryMemberRecords(@RequestHeader String accessToken, Page page) {
        String memberId = LoginHelper.getLoginId();
        GuessPriceActivity entity = guessPriceActivityService.getUsableActivity();
        if(null == entity || entity.getId() <= 0) {
            return new SerializeObjectError("00000003");
        }
        int total = guessRecordService.queryForCountByMemberId(memberId, entity.getId());
        page.setTotal(total);
        if (total > 0) {
            int offset = PaginationUtil.getOffset(page.getPageNum(), page.getPageSize());
            int size = PaginationUtil.getPageSize(page.getPageSize());
            if (page.getPageNum() == 0) {
                offset = 0;
                size = 0;
            }
            List<MemberGuessRecordBean> list = guessRecordService.queryForListByMemberId(memberId, entity.getId(), offset, size);
            return new SerializeObject<>(ResultType.NORMAL, new DataTable<MemberGuessRecordBean>(page.getPageNum(), page.getPageSize(), page.getTotal(), list));
        }
        return new SerializeObject<>(ResultType.NORMAL, new DataTable<MemberGuessRecordBean>(page.getPageNum(), page.getPageSize(), page.getTotal(), new ArrayList<MemberGuessRecordBean>()));
    }

    @GetMapping(value = "/usable")
    public SerializeObject getActivity() {
        GuessPriceActivity entity = guessPriceActivityService.getUsableActivity();
        if(null == entity || entity.getId() <= 0) {
            return new SerializeObjectError("00000003");
        }
        return new SerializeObject<>(ResultType.NORMAL, entity);
    }

    @GetMapping(value = "/recent/record")
    public SerializeObject<List<MemberGuessRecordBean>> queryMemberRecords() {
        List<MemberGuessRecordBean> list = guessRecordService.queryForListRecent30();
        if (list != null && list.size() > 0) {
            for (MemberGuessRecordBean bean : list) {
                if (StringUtils.isNotBlank(bean.getMobile())) {
                    bean.setMobile(StringUtils.substring(bean.getMobile(), 0, 3) +"****"+ StringUtils.substring(bean.getMobile(), 7));
                }
            }
        }
        return new SerializeObject<>(ResultType.NORMAL, list);
    }

    @GetMapping(value = "/record")
    public SerializeObject<MemberGuessRecordBean> queryMemberRecords(@RequestHeader String accessToken) {
        String memberId = LoginHelper.getLoginId();
        GuessPriceActivity entity = guessPriceActivityService.getUsableActivity();
        if(null == entity || entity.getId() <= 0) {
            return new SerializeObjectError("00000003");
        }
        MemberGuessRecordBean record = guessRecordService.selectTodayRecord(entity.getId(), memberId);
        return new SerializeObject<>(ResultType.NORMAL, record);
    }

    @GetMapping(value = "/yestoday/price")
    public SerializeObject getYestodayData() {
        GuessPriceActivity entity = guessPriceActivityService.getUsableActivity();
        if(null == entity || entity.getId() <= 0) {
            return new SerializeObjectError("00000003");
        }
        SimpleDateFormat format = new SimpleDateFormat(NORMAL_DATE_FORMAT);
        int currentDay = Integer.parseInt(StringUtils.removeAll(format.format(Calendar.getInstance().getTime()), MINUS));
        int startDay = Integer.parseInt(StringUtils.removeAll(entity.getStartDate(), MINUS));
        int endDay = Integer.parseInt(StringUtils.removeAll(entity.getEndDate(), MINUS));
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.DAY_OF_YEAR, -1);
        String someday = format.format(calendar.getTime()) + " " + entity.getTimePoint();
        JSONObject data = new JSONObject();
        if (startDay >= currentDay || currentDay > endDay) {
            SerializeObject<Double> result = priceService.getSomedayPrice(someday);
            if (result != null) {
                double price = result.getData();
                data.put("time", someday);
                data.put("price", new BigDecimal(price).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue());
                data.put("priceInterval", new BigDecimal(price-0.02).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue()+MINUS+new BigDecimal(price+0.02).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue());
            }
        } else {
            Double price = guessRecordService.selectYestodayFinalPrice();
            if (price == null) {
                SerializeObject<Double> result = priceService.getSomedayPrice(someday);
                if (result != null) {
                    price = result.getData();
                }
            }
            if (price != null && price > 0) {
                data.put("time", someday);
                data.put("price", new BigDecimal(price).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue());
                data.put("priceInterval", new BigDecimal(price-0.02).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue()+MINUS+new BigDecimal(price+0.02).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue());
            }
        }
        return new SerializeObject<>(ResultType.NORMAL, data);
    }

    @GetMapping(value = "/today/price")
    public SerializeObject getTodayData() {
        GuessPriceActivity entity = guessPriceActivityService.getUsableActivity();
        if(null == entity || entity.getId() <= 0) {
            return new SerializeObjectError("00000003");
        }
        double price = guessRecordService.selectTodayFinalPrice();
        JSONObject data = new JSONObject();
        SimpleDateFormat format = new SimpleDateFormat(NORMAL_DATE_FORMAT);
        Calendar calendar = Calendar.getInstance();
        String someday = format.format(calendar.getTime()) + " " + entity.getTimePoint();
        if (price > 0) {
            data.put("time", someday);
            data.put("price", new BigDecimal(price).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue());
            data.put("priceInterval", new BigDecimal(price-0.02).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue()+MINUS+new BigDecimal(price+0.02).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue());

        }
        return new SerializeObject<>(ResultType.NORMAL, data);
    }

    @GetMapping(value = "/got/num")
    public SerializeObject getGotNum(String someday) {
        GuessPriceActivity entity = guessPriceActivityService.getUsableActivity();
        if(null == entity || entity.getId() <= 0) {
            return new SerializeObjectError("00000003");
        }
        JSONObject result = new JSONObject();
        int num = guessRecordService.selectGotNum(entity.getId(), someday);
        if (num > 0) {
            result.put("gotNum", num);
            result.put("gold", entity.getGoldWeight()*1000/num/1000.0);
        } else {
            result.put("gotNum", 0);
            result.put("gold", 0);
        }
        return new SerializeObject<>(ResultType.NORMAL, result);
    }

    @GetMapping(value = "/guess/times")
    public SerializeObject getGuessTimes(@RequestHeader String accessToken) {
        String memberId = LoginHelper.getLoginId();
        GuessPriceActivity entity = guessPriceActivityService.getUsableActivity();
        int num = 0;
        if(null == entity || entity.getId() <= 0) {
            num = 0;
        }
        GuessJoinMember guessJoinMember = guessRecordService.findJoinInfo(memberId, entity.getId());
        if (guessJoinMember != null) {
            num = guessJoinMember.getBalance();
        } else {
            num = 1;
        }
        return new SerializeObject(ResultType.NORMAL, "00000001", num);
    }

        @PostMapping(value = "/guess")
    public SerializeObject guess(@RequestHeader String accessToken, double price) {
        String memberId = LoginHelper.getLoginId();
        //List<String> couponIds = properties.getCouponIds();
        GuessPriceActivity entity = guessPriceActivityService.getUsableActivity();
        if(null == entity || entity.getId() <= 0) {
            return new SerializeObjectError("25000031");
        }
        SimpleDateFormat format = new SimpleDateFormat(NORMAL_DATE_FORMAT);
        int currentDay = Integer.parseInt(StringUtils.removeAll(format.format(Calendar.getInstance().getTime()), MINUS));
        int startDay = Integer.parseInt(StringUtils.removeAll(entity.getStartDate(), MINUS));
        int endDay = Integer.parseInt(StringUtils.removeAll(entity.getEndDate(), MINUS));
        if (currentDay < startDay) {
            return new SerializeObjectError("25000031");
        }
        if (currentDay > endDay) {
            return new SerializeObjectError("25000032");
        }
        SimpleDateFormat timeFormat = new SimpleDateFormat("HHmm");
        int currentPoint = Integer.parseInt(timeFormat.format(new Date()));
        int startPoint = Integer.parseInt(StringUtils.removeAll(entity.getStartGuessPoint(), COLON));
        int endPoint = Integer.parseInt(StringUtils.removeAll(entity.getEndGuessPoint(), COLON));
        if (currentPoint < startPoint) {
            return new SerializeObjectError("25000031");
        }
        if (currentPoint > endPoint) {
            return new SerializeObjectError("25000033");
        }
        Calendar calendar = Calendar.getInstance();
        if (calendar.get(Calendar.DAY_OF_WEEK)==Calendar.SATURDAY || calendar.get(Calendar.DAY_OF_WEEK)==Calendar.SUNDAY) {
            return new SerializeObjectError("25000031");
        }
        /*MemberGuessRecordBean record = guessRecordService.selectTodayRecord(entity.getId(), memberId);
        if (record != null && record.getRecordId() > 0) {
            return new SerializeObjectError("25000034");
        }*/
        GuessJoinMember guessJoinMember = guessRecordService.findJoinInfo(memberId, entity.getId());
        if (guessJoinMember != null) {
            if (guessJoinMember.getBalance() < 1) {
                return new SerializeObjectError("25000034");
            }
        }
        GuessRecord guessRecord = new GuessRecord();
        guessRecord.setActivityId(entity.getId());
        guessRecord.setMemberId(memberId);
        guessRecord.setGuessPrice(price);
        if (guessRecordService.saveRecord(guessRecord)) {
            return new SerializeObject(ResultType.NORMAL, "00000001");
        } else {
            return new SerializeObject(ResultType.ERROR, "00000005");
        }
    }

    @GetMapping(value = "/coupon/amount")
    public SerializeObject getCouponAmount(String someday) {
        if (StringUtils.isBlank(someday)) {
            return new SerializeObjectError("00000002");
        }
        GuessPriceActivity entity = guessPriceActivityService.getUsableActivity();
        if(null == entity || entity.getId() <= 0) {
            return new SerializeObjectError("25000031");
        }
        SimpleDateFormat format = new SimpleDateFormat(NORMAL_DATE_FORMAT);
        int currentDay = Integer.parseInt(StringUtils.removeAll(format.format(Calendar.getInstance().getTime()), MINUS));
        int startDay = Integer.parseInt(StringUtils.removeAll(entity.getStartDate(), MINUS));
        int endDay = Integer.parseInt(StringUtils.removeAll(entity.getEndDate(), MINUS));
        if (currentDay < startDay) {
            return new SerializeObjectError("25000031");
        }
        if (currentDay > endDay) {
            return new SerializeObjectError("25000032");
        }
        String amount = "";
        try {
            Calendar calendar = Calendar.getInstance();
            Date date = format.parse(someday);
            calendar.setTime(date);
            if (calendar.get(Calendar.DAY_OF_WEEK)==Calendar.SATURDAY || calendar.get(Calendar.DAY_OF_WEEK)==Calendar.SUNDAY) {
                return new SerializeObjectError("25000031");
            }
            int week = calendar.get(Calendar.DAY_OF_WEEK);
            week = week - 2;
            if (week < 0) {
                week = 0;
            }
            List<String> couponIds = properties.getCouponIds();
            SerializeObject<CouponRepertoryBean> bean = couponRepertoryService.get(couponIds.get(week));
            if (bean != null) {
                CouponRepertoryBean couponRepertoryBean = bean.getData();
                if (couponRepertoryBean != null) {
                    amount = couponRepertoryBean.getAmount();
                }
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return new SerializeObject(ResultType.NORMAL, "00000001", amount);
    }

    @PostMapping(value = "/share")
    public SerializeObject share(@RequestHeader String accessToken, int recordId) {
        GuessPriceActivity entity = guessPriceActivityService.getUsableActivity();
        if(null == entity || entity.getId() <= 0) {
            return new SerializeObjectError("25000031");
        }
        SimpleDateFormat format = new SimpleDateFormat(NORMAL_DATE_FORMAT);
        int currentDay = Integer.parseInt(StringUtils.removeAll(format.format(Calendar.getInstance().getTime()), MINUS));
        int startDay = Integer.parseInt(StringUtils.removeAll(entity.getStartDate(), MINUS));
        int endDay = Integer.parseInt(StringUtils.removeAll(entity.getEndDate(), MINUS));
        if (currentDay < startDay) {
            return new SerializeObjectError("25000031");
        }
        if (currentDay > endDay) {
            return new SerializeObjectError("25000032");
        }
        GuessRecord record = guessRecordService.findById(recordId);
        if (record == null || record.getId() == 0) {
            return new SerializeObjectError("25000031");
        }
        int endPoint = Integer.parseInt(StringUtils.removeAll(entity.getEndGuessPoint(), COLON));
        if (!guessRecordService.share(record.getMemberId(), entity.getId(), endPoint)) {
            return new SerializeObject(ResultType.ERROR, "00000005");
        }
        SerializeObject<MemberUserBean> memberBean = memberUserService.findById(record.getMemberId());
        String mobile = "";
        if (memberBean != null && memberBean.getData() != null) {
            MemberUserBean memberUserBean = memberBean.getData();
            mobile = memberUserBean.getMobile();
        } else {
            return new SerializeObject(ResultType.ERROR, "00000005");
        }
        if (record.getGuessResult() == 1 || record.getShareStatus() == 2) {
            return new SerializeObjectError("00000005");
        }
        String guessDate = UF.getFormatDate(record.getGuessTime());
        String couponId = null;
        if (record.getGuessResult() == 2) {
            int num = guessRecordService.selectGotNum(entity.getId(), guessDate);
            if (num > 0) {
                record.setGotGold(entity.getGoldWeight()*1000/num/1000.0);
            }
        } else {
            if (StringUtils.isNotBlank(entity.getCouponIds())) {
                String[] couponIds = StringUtils.split(entity.getCouponIds(), ",");
                couponId = couponIds[ThreadLocalRandom.current().nextInt(0, couponIds.length)];
                SerializeObject<CouponRepertoryBean> bean = couponRepertoryService.get(couponId);
                if (bean != null) {
                    CouponRepertoryBean couponRepertoryBean = bean.getData();
                    if (couponRepertoryBean != null) {
                        record.setCouponAmount(Double.parseDouble(couponRepertoryBean.getAmount()));
                    }
                }
            }
        }
        /*if (record.getGuessResult() == 3) {
            try {
                Calendar calendar = Calendar.getInstance();
                Date date = format.parse(guessDate);
                calendar.setTime(date);

                int week = calendar.get(Calendar.DAY_OF_WEEK);
                week = week - 2;
                if (week < 0) {
                    week = 0;
                }
                List<String> couponIds = properties.getCouponIds();
                couponId = couponIds.get(week);
                SerializeObject<CouponRepertoryBean> bean = couponRepertoryService.get(couponIds.get(week));
                if (bean != null) {
                    CouponRepertoryBean couponRepertoryBean = bean.getData();
                    if (couponRepertoryBean != null) {
                        record.setCouponAmount(Double.parseDouble(couponRepertoryBean.getAmount()));
                    }
                }
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }*/

        if (guessRecordService.share(record, couponId, mobile)) {
            return new SerializeObject(ResultType.NORMAL, "00000001");
        } else {
            return new SerializeObject(ResultType.ERROR, "00000005");
        }
    }

    @PostMapping(value = "/share/times")
    public SerializeObject shareForTimes(@RequestHeader String accessToken) {
        String memberId = LoginHelper.getLoginId();
        GuessPriceActivity entity = guessPriceActivityService.getUsableActivity();
        if(null == entity || entity.getId() <= 0) {
            return new SerializeObjectError("25000031");
        }
        SimpleDateFormat format = new SimpleDateFormat(NORMAL_DATE_FORMAT);
        int currentDay = Integer.parseInt(StringUtils.removeAll(format.format(Calendar.getInstance().getTime()), MINUS));
        int startDay = Integer.parseInt(StringUtils.removeAll(entity.getStartDate(), MINUS));
        int endDay = Integer.parseInt(StringUtils.removeAll(entity.getEndDate(), MINUS));
        if (currentDay < startDay) {
            return new SerializeObjectError("25000031");
        }
        if (currentDay > endDay) {
            return new SerializeObjectError("25000032");
        }
        int endPoint = Integer.parseInt(StringUtils.removeAll(entity.getEndGuessPoint(), COLON));
        if (guessRecordService.share(memberId, entity.getId(), endPoint)) {
            return new SerializeObject(ResultType.NORMAL, "00000001");
        } else {
            return new SerializeObject(ResultType.ERROR, "00000005");
        }
    }
}
